﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;

namespace scanner
{
    public partial class MainForm : Form
    {
        public static MainForm mainForm;

        String ICCode;
        String JobNum;
        Hashtable htECs = new Hashtable();
        HashSet<String> hs = new HashSet<string>();
        bool isLinkDB = false;          //是否连接数据库，调试时跳过数据库连接用，默认true

        int total;      //总测试数量
        int passNum;    //通过数量
        int failNum;    //fail数量

        bool isPackage = false;     //是否打包
        int packageNum;             //每箱数量
        int currentNum;             //当前包装数量
        StreamWriter sw;
        string packageDataPath = "D://PackageData";

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x2000000;
                return cp;
            }
        }

        /// <summary>
        /// CheckForIllegalCrossThreadCalls = false;
        /// mainForm = this;
        /// 其他类就可以调用该窗体类或其控件
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            mainForm = this;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (isLinkDB)
            {
                utils.SqlHelper.connectDB();
            }

            lvInit();
            tbSN0.Focus();
        }

        private void lvInit()
        {
            lvDisplay.Columns.Add("序号", 50, HorizontalAlignment.Center);
            lvDisplay.Columns.Add("EC", 100, HorizontalAlignment.Center);
            lvDisplay.Columns.Add("description", 160, HorizontalAlignment.Center);
            lvDisplay.Columns.Add("LL", 100, HorizontalAlignment.Center);
            lvDisplay.Columns.Add("value", 100, HorizontalAlignment.Center);
            lvDisplay.Columns.Add("UL", 100, HorizontalAlignment.Center);
            lvDisplay.Columns.Add("测试结果", 100, HorizontalAlignment.Center);
            lvDisplay.Columns.Add("测试时间", 100, HorizontalAlignment.Center);
            lvDisplay.View = View.Details;
        }

        /// <summary>
        /// lvDisplay刷新
        /// </summary>
        /// <param name="ec"></param>
        public void lvUpdate(domain.EC ec)
        {
            int total = lvDisplay.Items.Count;
            lvDisplay.BeginUpdate();
            #region
            ListViewItem item = new ListViewItem();
            item = lvDisplay.Items.Add((total + 1).ToString());     //新增行
            item.SubItems.Add(ec.EcCode.ToString());
            item.SubItems.Add(ec.Desc);
            item.SubItems.Add(ec.LLimit.ToString());
            item.SubItems.Add(ec.Value.ToString());
            item.SubItems.Add(ec.ULimit.ToString());
            item.SubItems.Add(ec.Result ? "pass" : "fail");
            item.SubItems.Add(ec.CostTime.ToString());
            if (!ec.Result)
            {
                item.BackColor = Color.IndianRed;
            }
            else
            {
                item.BackColor = Color.MediumSeaGreen;
            }
            #endregion
            lvDisplay.EndUpdate();
        }

        /// <summary>
        /// 清空lvDisplay
        /// </summary>
        public void lvClear()
        {
            lvDisplay.Items.Clear();
            if (lvDisplay.Items.Count > 0)
                lvDisplay.Items.RemoveAt(0);
        }

        public void gp3Update()
        {
            tbTotal.Text = total.ToString();
            tbPass.Text = passNum.ToString();
            tbFail.Text = failNum.ToString();
            double passRate = passNum / total * 100;
            tbPassRate.Text = String.Format("{0:F}%", passRate);     //默认保留两位小数
            if (passRate < 90)
            {
                tbPassRate.BackColor = Color.IndianRed;
            }
            else
            {
                tbPassRate.BackColor = Color.MediumSeaGreen;
            }
        }

        /// <summary>
        /// 通过ICCode读取xml中的gtin和EC
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure_Click(object sender, EventArgs e)
        {
            domain.EC ecST = new domain.EC(0, "STOK", 0, 0, "1");
            domain.EC ecFCT = new domain.EC(1, "FCTOK", 0, 0, "1");
            htECs.Add("STOK", ecST);
            htECs.Add("FCTOK", ecFCT);           

            //读ICCode，需要检测NFC的
            hs = utils.XMLHelper.readICCodes();

            //读包装数量
            DirectoryInfo binPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            utils.IniHelper.setFilePath(binPath.Parent.Parent.FullName + String.Format("\\config\\{0}", "packages.ini"));
            string packageNum_ = utils.IniHelper.readFile(tbICCode.Text.Trim());
            int.TryParse(packageNum_, out packageNum);
            tbPackage.Text = packageNum.ToString();

            btnSure.BackColor = Color.MediumSeaGreen;
            tbSN.Focus();
        }


        public Hashtable startTest(Hashtable ht, String sn)
        {
            Hashtable htTestResult = new Hashtable();

            domain.EC ec = null;
            if (utils.ECHelper.getFailedCount(htTestResult) == -1)
            {
                ec = utils.ECHelper.GetEC(ht, "STOK");
                if (utils.SqlHelper.STisPass(sn))
                    ec.Value = 0;
                utils.ECHelper.isPass(ec, htTestResult);
                ec.Value = -1;
            }

            if (utils.ECHelper.getFailedCount(htTestResult) == -1)
            {
                ec = utils.ECHelper.GetEC(ht, "FCTOK");
                if (hs.Contains(ICCode))
                {
                    if (utils.SqlHelper.FCTAndNFCisPass(sn))
                        ec.Value = 0;
                }
                else
                {
                    if (utils.SqlHelper.FCTisPass(sn))
                        ec.Value = 0;
                }
                utils.ECHelper.isPass(ec, htTestResult);
                ec.Value = -1;
            }

            return htTestResult;
        }

        public void showFail(Hashtable ht)
        {
            if (utils.ECHelper.getFailedCount(ht) > 0)
            {
                utils.Media.Error();
                MessageBox.Show("ST或FCT未测试通过");
            }
            else {
                utils.Media.Pass();
            }
        }

        private void rbYes_CheckedChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbPackage.Text.Trim()) || !int.TryParse(tbPackage.Text.Trim(), out packageNum))
            {
                MessageBox.Show("必须设置每箱包装数量", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                rbNo.Checked = true;
                tbPackage.Text = "";
                tbPackage.Focus();
            }
            else { 
                isPackage=true;

                //创建txt保存打包信息
                ICCode = tbICCode.Text.Trim();
                packageDataPath = packageDataPath + "//" + ICCode + "_" + DateTime.Today.Year + DateTime.Today.Month + ".txt";
                string dir = Path.GetDirectoryName(packageDataPath);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) {
                    Directory.CreateDirectory(dir);
                }
                if (!File.Exists(dir)) {
                    sw = new StreamWriter(packageDataPath, true, Encoding.UTF8);
                    sw.AutoFlush = true;
                }

                //保存
                utils.IniHelper.write("packages", ICCode, tbPackage.Text.Trim());

                tbPackage.Enabled = false;
                tbSN.Focus();
            }
        }

        private void tbSN0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                String sn = tbSN0.Text.Trim();
                ICCode = sn.Substring(12, 11);
                JobNum = sn.Substring(5, 7);
                tbICCode.Text = ICCode;
                tbJobNum.Text = JobNum;
                btnSure.Focus();
            }            
        }

        private void tbSN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter) {
                return;
            }

            if (!isLinkDB)
            {
                return;
            }

            //清空lvDisplay
            lvClear();

            String sn = tbSN.Text.Trim();
            Hashtable htTestResult = startTest(htECs, sn);

            //将测试结果写入到服务器
            String[] tempStr = utils.SqlHelper.createDataStr(sn, htTestResult);
            utils.SqlHelper.upToDB(tempStr[0], tempStr[1]);

            //gbState
            total++;
            if (utils.ECHelper.getFailedCount(htTestResult) > 0)
            {
                failNum++;
            }
            else
            {
                passNum++;
                currentNum++;
            }
            gp3Update();

            //提示未通过
            showFail(htTestResult);

            //打包提示
            if (isPackage)
            {                
                if (currentNum == 1)
                {
                    sw.WriteLine("**************************************************");
                }
                sw.WriteLine(sn);

                if (currentNum == packageNum)
                {
                    MessageBox.Show("包箱已满，请封箱", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    currentNum = 0;
                }
            }

            //准备下一次测试
            tbSN.Text = "";
            tbSN.Focus();
        }

        private void btnManualPackaged_Click(object sender, EventArgs e)
        {
            currentNum = 0;
            //准备下一次测试
            tbSN.Text = "";
            tbSN.Focus();
        }
    }
}
